package com.qf.flash.ui.chat;

import android.app.Dialog;
import android.content.Intent;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.easeui.widget.EaseImageView;
import com.qf.dblib.dao.entity.ChatUserBean;
import com.qf.dblib.dao.entity.InviteMessage;
import com.qf.flash.R;
import com.qf.flash.constant.Constant;
import com.qf.flash.http.response.SysMsgResponse;
import com.qf.flash.mvp.contract.NewFriendInviteContract;
import com.qf.flash.mvp.contract.SysMsgContract;
import com.qf.flash.mvp.presenter.NewFriendInvitePresenter;
import com.qf.flash.mvp.presenter.SysMsgPresenter;
import com.qf.flash.utils.AppToast;
import com.qf.flash.utils.LogUtil;
import com.qf.flash.utils.MyUtil;
import com.qf.flash.widget.ClearEditText;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.widget.CustomProgressDialog;

import org.litepal.LitePal;

import java.util.List;

import static com.qf.flash.constant.Constants.BEINVITEED;

/**
 * 创建日期：2020/2/22 on 20:27
 * 描述:   主页会话列表窗口
 */
public class ChatFragment extends EaseConversationListFragment implements View.OnClickListener,NewFriendInviteContract.View, SysMsgContract.View {


    private Dialog dialog;
    private TextView tv_cancel, tv_sure;
    private ImageView ivAdd, ivList;
    private TextView tvMsg1;
    private TextView tvUnread1;
    private ClearEditText nameText;
    private CustomProgressDialog addDialog;
    protected List<EMGroup> grouplist;
    protected static final String ACTION_TYPING_BEGIN = "TypingBegin";
    private NewFriendInvitePresenter newFriendInvitePresenter;
    private SysMsgPresenter mSysMsgPresenter;
    private TextView tvSysMsg;
    private TextView tvSysMsgTime;
    @Override
    protected void initView() {
        super.initView();
        initDialog();
        ivList = getView().findViewById(R.id.iv_list);
        ivAdd = getView().findViewById(R.id.iv_add);
        ivAdd.setOnClickListener(view -> {
            dialog.show();
        });

        ivList.setOnClickListener(view -> {
            ContactListActivity.start(getActivity());
            // ----------------------------------------------------------------------------------

        });

        initBottomView();
       /* for (EMConversation emConversation : conversationList) {
            GameDetailResponse group = LitePal.where("uid = ?", emConversation.conversationId()).findLast(GameDetailResponse.class);


        }*/
       newFriendInvitePresenter = new NewFriendInvitePresenter();
       newFriendInvitePresenter.attachView(this);
       mSysMsgPresenter = new SysMsgPresenter();
       mSysMsgPresenter.attachView(this);

    }


    @Override
    public void refresh() {
        super.refresh();
        List<InviteMessage> allInvite = LitePal.where("status = ?", BEINVITEED).
                order("time desc").find(InviteMessage.class);
        if (allInvite.size() > 0) {
            for (InviteMessage inviteMessage : allInvite) {
                String status = inviteMessage.getStatus();
                LogUtil.d("  ---   " + status);
                if (status.equals(BEINVITEED)) {
                    LogUtil.d("mainEMClientChat:" + "----您有新的好友申请！" + inviteMessage.getFrom());
                    tvMsg1.setText("您有新的好友申请，请注意查收！");
                    tvUnread1.setVisibility(View.VISIBLE);
                    tvUnread1.setText(allInvite.size() + "");
                }
            }

        } else {
            tvMsg1.setText("暂无新的消息！");
            tvUnread1.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        newFriendInvitePresenter.detachView();
        mSysMsgPresenter.detachView();
    }

    @Override
    public void onResume() {
        super.onResume();
        mSysMsgPresenter.getSysMsg(1,1);
    }

    // 底部固定栏
    private void initBottomView() {

        View bottomView = LayoutInflater.from(getActivity()).inflate(com.hyphenate.easeui.R.layout.ease_chat_bottom, null);
        conversationListView.addHeaderView(bottomView);

        EaseImageView imageView1 = bottomView.findViewById(R.id.avatar1);
        tvUnread1 = bottomView.findViewById(R.id.unread_msg_number1);
        TextView tvName1 = bottomView.findViewById(R.id.name1);
        TextView tvTime1 = bottomView.findViewById(R.id.time1);
        tvMsg1 = bottomView.findViewById(R.id.message1);
        tvMsg1.setText("没有新的消息");
        Glide.with(getActivity()).load(R.mipmap.chat_yz).apply(new RequestOptions().circleCrop()).into(imageView1);
        tvName1.setText("好友验证");
        RelativeLayout rlYz = bottomView.findViewById(R.id.list_itease_layout1);
        rlYz.setOnClickListener(this);
        EaseImageView imageView = bottomView.findViewById(R.id.avatar);
        TextView tvUnread = bottomView.findViewById(R.id.unread_msg_number);
        TextView tvName = bottomView.findViewById(R.id.name);
        tvSysMsgTime  = bottomView.findViewById(R.id.time);
        tvSysMsg = bottomView.findViewById(R.id.message);
        tvSysMsg.setText("没有新的消息");
        Glide.with(getContext()).load(R.mipmap.chat_tip).apply(new RequestOptions().circleCrop()).into(imageView);
        tvName.setText("系统通知");
        RelativeLayout rlTip = bottomView.findViewById(R.id.list_itease_layout);
        rlTip.setOnClickListener(this);

    }

    /**
     * 添加好友dialog
     */
    private void initDialog() {
        dialog = new Dialog(getContext(), R.style.custom_dialog2);

        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);

        View v = View.inflate(getContext(), R.layout.dialog_add_friend, null);
        window.setContentView(v);
//        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
        WindowManager.LayoutParams p = window.getAttributes();
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay();
        p.width = (int) (d.getWidth() * 0.82);
        p.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(p);

        tv_sure = v.findViewById(R.id.tv_sure);
        tv_cancel = v.findViewById(R.id.tv_cancel);
        nameText = v.findViewById(R.id.nameText);
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyUtil.isNullOrEmpty(nameText.getText().toString())) {
                    AppToast.shake(nameText);
                    AppToast.showToast("ID号不能为空！");
                } else {
                    addDialog.show();
                    newFriendInvitePresenter.addFriend(nameText.getText().toString());
                }

            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        addDialog = new CustomProgressDialog(getActivity());
        addDialog.setTipText(R.string.Is_sending_a_request);
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int headerViewsCount = conversationListView.getHeaderViewsCount();
                EMConversation conversation = conversationListView.getItem(position- headerViewsCount);
                String username = conversation.conversationId();
                String currentUser = EMClient.getInstance().getCurrentUser();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it's group chat
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.list_itease_layout1://好友验证
                NewFriendsMsgActivity.start(getActivity());
                break;
            case R.id.list_itease_layout:// 系统通知
                SystemNotificationActivity.start(getActivity());
                break;
        }
    }


    @Override
    public void setUi(List<ChatUserBean> chatUserBeans) {

    }

    @Override
    public void addFriendResult(boolean success) {
        dialog.dismiss();
        addDialog.dismiss();
    }

    @Override
    public void showLoading() {
        addDialog.show();
    }

    @Override
    public void hideLoading() {
        if (addDialog!= null)
            addDialog.dismiss();
    }

    @Override
    public void showMessage(String msg) {
        FlashLib.showToast(msg);
    }

    @Override
    public void onError(ApiException e) {
        FlashLib.showToast(e.getMessage());
        dialog.dismiss();
        addDialog.dismiss();
    }

    @Override
    public void setSysMsgData(List<SysMsgResponse> responses, int totalPage) {
        if (responses != null && responses.size() > 0) {
            SysMsgResponse sysMsgResponse = responses.get(0);
            tvSysMsg.setText(sysMsgResponse.getContent());
            tvSysMsgTime.setText(sysMsgResponse.getShowTime());
        }
    }
}
